//
//  SISSTenantProgressViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2017/12/21.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSTenantProgressViewController.h"
#import "SISSMorePopupView.h"
#import "SISSProgressCell.h"
#import "SISSHistoryProgressCell.h"
#import "SISSProgressBottomView.h"
#import "SISSChatViewController.h"

#import "SISSTenantProgressModel.h"
#import "SISSRentOutModel.h"
#import "SISSTenantProgressRecordInfoModel.h"
#import "SISSTenantEntrustContractModel.h"

#import "SISSIntendTenantDetailViewController.h"
#import "SISSRentOutDetailViewController.h"
#import "SISSTenantDetailViewController.h"

#import "SISSUploadTenantEntrustContractViewController.h"
#import "SISSTenantEntrustContractShowViewController.h"

#import "SISSConfirmIntentionLeaseViewController.h"

#import "SISSTenantReservationRecordViewController.h"

#import "SISSUploadTenancyContractViewController.h"
#import "SISSTenancyContractShowViewController.h"
#import "SISSTenancyContractModel.h"

#import "SISSProgressWebViewController.h"
#import "SISSTextShowViewController.h"

#import "SISSNetworkingManager+TenantProgress.h"
#import "SISSNetworkingManager+Progress.h"

#import "SISSCommentListViewController.h"


static NSString *tenantProgressCellReuseID = @"tenantProgressCellReuseID";
static NSString *tenantHistoryProgressCellReuseID = @"tenantHistoryProgressCellReuseID";
@interface SISSTenantProgressViewController ()<UITableViewDelegate,UITableViewDataSource,SISSMorePopupViewDelegate,SISSProgressBottomViewDelegate>
/* tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;
/* bottomView */
@property (weak, nonatomic) SISSProgressBottomView *bottomView;

/// 进度信息记录模型
@property (strong, nonatomic) SISSTenantProgressRecordInfoModel *tenantProgressInfoModel;

/* 数据 */
@property (copy, nonatomic) NSArray *dataArr;

@end

@implementation SISSTenantProgressViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"求租进度详情";
    
    WeakSelf
    [kSISSRefresh prepareHeaderRefresh:self.tableView loadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeUpDown;
        // 获取合作记录时间和id信息
        [weakSelf requestTenantProgressRecordInfo];
    }];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 获取合作记录时间和id信息
    [self requestTenantProgressRecordInfo];
}

#pragma mark - 代理
#pragma mark -- UITableViewDelegate & UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    if (self.isHistory) {
//        SISSHistoryProgressCell *cell = [tableView dequeueReusableCellWithIdentifier:tenantHistoryProgressCellReuseID forIndexPath:indexPath];
//        cell.rowCount = self.dataArr.count - 1;
//        // 优化从外面点击进入的体验
//        NSInteger progress = self.tenantProgressModel.businessType == 2 ?  : self.tenantProgressInfoModel.progress;
//        cell.progress = progress > 4 ? progress + 1 : progress;
//        cell.index = indexPath.row;
//        cell.title = self.dataArr[indexPath.row];
//        cell.timeStr = [self getTimeStrWithIndex:indexPath.row];
//        // 判断cell能否点击跳转
////        NSInteger index = (self.tenantProgressInfoModel ? self.tenantProgressInfoModel.progress : self.tenantProgressModel.progress);
//        cell.userInteractionEnabled = indexPath.row <= (progress > 4 ? progress + 1 : progress);
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        return cell;
//    } else
    {
        SISSProgressCell *cell = [tableView dequeueReusableCellWithIdentifier:tenantProgressCellReuseID forIndexPath:indexPath];
        
        // 优化从外面点击进入的体验
        NSInteger progress = self.tenantProgressModel.businessType == 2 ? self.tenantProgressInfoModel.progress -1 : self.tenantProgressInfoModel.progress;
        progress = progress > 5 ? progress + 1 : progress;
        cell.isFisrtCell = indexPath.row == 0;
        cell.isLastCell = indexPath.row == self.dataArr.count - 1;
        if (progress > indexPath.row) {
            cell.progressStatus = 1;
            cell.topIsDash = NO;
            cell.bottomIsDash = NO;
            cell.userInteractionEnabled = YES;
        } else if (progress == indexPath.row) {
            cell.topIsDash = NO;
            cell.progressStatus = self.isHistory ? 3 : 2;
            cell.bottomIsDash = YES;
            cell.userInteractionEnabled = !self.isHistory;
        } else {
            cell.progressStatus = 3;
            cell.topIsDash = YES;
            cell.bottomIsDash = YES;
            cell.userInteractionEnabled = NO;
        }
        cell.title = self.dataArr[indexPath.row];
        cell.timeStr = [self getTimeStrWithIndex:indexPath.row];
        // 判断cell能否点击跳转

//        cell.userInteractionEnabled = indexPath.row <= (progress > 4 ? progress + 1 : progress);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger index = self.tenantProgressModel.businessType == 1 ? indexPath.row : indexPath.row + 1;
//    index = self.tenantProgressInfoModel.payType == 1 ? index : index -1;
    switch (index) {
        case 0: { // 承租方发布求租信息
            SISSTenantDetailViewController *vc = [[SISSTenantDetailViewController alloc] init];
            vc.tenantModel = self.tenantProgressModel.rent;
            vc.isHiddenBottomButton = YES;
            [self.navigationController pushViewController:vc animated:YES];
            
        }
            break;
            
        case 1: { // 中介推荐出租房源、承租方确定意向
 
            if (self.tenantProgressModel.businessType == 1) {
//                SISSRentOutDetailViewController *vc = [[SISSRentOutDetailViewController alloc] init];
//                vc.title = @"意向出租房源";
//                vc.arbpId = self.tenantProgressModel.arbpId;
//                vc.isHiddenBottomButton = YES;
//                [self.navigationController pushViewController:vc animated:YES];
                SISSIntendTenantDetailViewController *vc = [[SISSIntendTenantDetailViewController alloc] init];
                vc.arbpId = self.tenantProgressModel.arbpId;
                vc.isHiddenBottom = YES;
                [self.navigationController pushViewController:vc animated:YES];
                
            } else {
                SISSIntendTenantDetailViewController *vc = [[SISSIntendTenantDetailViewController alloc] init];
                vc.arbpId = self.tenantProgressModel.arbpId;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
            
        case 2: { // 上传已签署的《物业租赁承租方委托协议》
            
            if (self.tenantProgressInfoModel.hasCommissionContract) {
                SISSTenantEntrustContractShowViewController *vc = [[SISSTenantEntrustContractShowViewController alloc] init];
                vc.abpId = self.tenantProgressModel.arbpId;
                vc.popBackClassType = SISSProgressPopBackClassTypeTenant;
                vc.isHistory = self.isHistory;
                [self.navigationController pushViewController:vc animated:YES];
            } else {
                if (self.tenantProgressInfoModel.businessStatus == 2) {
                    [self alertActionAlertWithTitle:@"提示" message:@"对方已开启拒绝接收您的请求"];
                    return;
                }
                SISSUploadTenantEntrustContractViewController *vc = [[SISSUploadTenantEntrustContractViewController alloc] init];
                vc.abpId = self.tenantProgressModel.arbpId;
                vc.popBackClassType = SISSProgressPopBackClassTypeTenant;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
            
        case 3: { // 预约-承租方实地看房
            
            SISSTenantReservationRecordViewController *vc = [[SISSTenantReservationRecordViewController alloc] init];
            vc.tenantProgressModel = self.tenantProgressModel;
            vc.isHistory = self.isHistory;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case 4: { // 确定租赁房源
            
            SISSConfirmIntentionLeaseViewController *vc = [[SISSConfirmIntentionLeaseViewController alloc] init];
            vc.tenantProgressModel = self.tenantProgressModel;
            vc.tenantProgressRecordInfoModel = self.tenantProgressInfoModel;
            vc.hasConfirm = self.tenantProgressInfoModel.tradeBusinessType > 0;
            vc.isHistory = self.isHistory;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case 5: { // 上传已签署的《物业租赁及经纪合同》
            
            if (self.tenantProgressInfoModel.hasleaseContract) {
                SISSTenancyContractShowViewController *vc = [[SISSTenancyContractShowViewController alloc] init];
                vc.tenantProgressModel = self.tenantProgressModel;
                vc.tenantProgressRecordInfoModel = self.tenantProgressInfoModel;
                vc.isHistory = self.isHistory;
                [self.navigationController pushViewController:vc animated:YES];
            } else {
                if (self.tenantProgressInfoModel.businessStatus == 2) {
                    [self alertActionAlertWithTitle:@"提示" message:@"对方已开启拒绝接收您的请求"];
                    return;
                }
                
                SISSUploadTenancyContractViewController *vc = [[SISSUploadTenancyContractViewController alloc] init];
                vc.tenantProgressModel = self.tenantProgressModel;
                vc.tenantProgressRecordInfoModel = self.tenantProgressInfoModel;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
            
        case 6: { // 出租方将物业交承租方使用
            SISSProgressWebViewController *vc = [[SISSProgressWebViewController alloc] init];
            vc.title = @"出租方将物业交承租方使用";
            vc.url = URL_PROGRESS_DELIVERHOUSE_INFO;
            [self.navigationController pushViewController:vc animated:YES];
//            SISSTextShowViewController *vc = [[SISSTextShowViewController alloc] init];
//            vc.title = @"出租方将物业交承租方使用";
//            vc.textStr = @"注意事项：\n1、交房屋时，三方检验房屋现况，核对设备和租赁合同清单是否一致，税费、水电、煤气、电话、有线电视及管理费用是否结算，无异议后将钥匙交与承租方；\n2.出租方及时办理物业租赁备案，承租方积极配合。";
//            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case 7: { // 服务评价
            SISSCommentListViewController *vc = [[SISSCommentListViewController alloc] init];
            vc.tenantProgressModel = self.tenantProgressModel;
            vc.commentType = 10;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 88;
}

#pragma mark -- SISSMorePopupViewDelegate 删除 举报
- (void)morePopupViewSelectedWithIndex:(NSInteger)index {
    
        if (self.tenantProgressInfoModel.progress > 2) { // 举报
            [self reportTenant];
        } else {
        if (index == 0) { // 删除
            
            NSString *str = @"删除后不可恢复，您确定删除吗？";
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.alignment = NSTextAlignmentLeft;
            
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13], NSForegroundColorAttributeName: COLOR(0x334A60), NSParagraphStyleAttributeName: paragraphStyle}];
            
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"删除" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            [alertC setValue:attr forKey:@"attributedMessage"];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"取消");
            }];
            [alertC addAction:cancelAction];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"确定");
                
                [self deleteTenantProgress];
            }];
            [alertC addAction:okAction];
            
            [self presentViewController:alertC animated:YES completion:nil];
        } else { // 举报
            [self reportTenant];
        }
    }
}

#pragma mark -- SISSProgressBottomViewDelegate 底部头像、电话、在线咨询
- (void)clickBottomButtonWithIndex:(NSInteger)index {
    
    if (self.tenantProgressInfoModel.businessStatus == 2 && index == 1) {
        [self alertActionAlertWithTitle:@"提示" message:@"对方已开启拒绝接收您的请求"];
        return;
    }
    if (index == 0) { // 点击头像或名字的
        NSLog(@"人员信息");
        //        [kNetworkManager requestPersonInfoWithSpId:self.tenantProgressModel.spId success:^(SISSPersonInfoModel *personInfo) {
        //
        //            SISSInfomationViewController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"SISSInfomationViewController"];
        //            vc.personInfo = personInfo;
        //
        //            vc.spId = self.tenantProgressModel.spId;
        //            [self.navigationController pushViewController:vc animated:YES];
        //
        //        } failed:^(NSError *error) {
        //
        //            NSLog(@"%@",error);
        //        }];
            } else if (index == 1) { // 点击拨打电话
        
                if (self.tenantProgressInfoModel.progress < 3) {
                    [self alertActionAlertWithTitle:@"不能拨号" message:@"没有签署委托合同，暂不能拨号！"];
                } else {
        
                    UIWebView * callWebview = [[UIWebView alloc] init];
                    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",self.tenantProgressInfoModel.mobile]]]];
                    [[UIApplication sharedApplication].keyWindow addSubview:callWebview];
                }
            } else { // 点击联系人
        
                SISSChatViewController *chatVC = [[SISSChatViewController alloc] initWithConversationChatter:self.tenantProgressInfoModel.imAccount conversationType:EMConversationTypeChat];
                SISSContactModel *model = [[SISSContactModel alloc] init];
                model.name = self.tenantProgressInfoModel.name;
                model.accountType = 3;
                model.portrait = self.tenantProgressInfoModel.portrait;
                chatVC.contactModel = model;
                chatVC.title = self.tenantProgressInfoModel.name;
                [self.navigationController pushViewController:chatVC animated:YES];
    }
}

#pragma mark - 点击事件
#pragma mark -- 右上角更多按钮点击事件
- (void)rightMoreItemClickAction {
    
    NSArray *titleArr =  self.tenantProgressModel.progress > 2 ? @[@"举报"] : @[@"删除", @"举报"];
    SISSMorePopupView *moreView = [[SISSMorePopupView alloc] initWithTitles:titleArr];
    moreView.delegate = self;
    [moreView show];
}

#pragma mark - 加载数据

#pragma mark -- 获取求租进度记录时间和id信息
- (void)requestTenantProgressRecordInfo {
    self.tenantProgressInfoModel = [SISSTenantProgressRecordInfoModel new];
    self.tenantProgressInfoModel.progress = self.tenantProgressModel.progress;
    WeakSelf
    [kNetworkManager requestTenantProgressRecordInfoWithArbpId:self.tenantProgressModel.arbpId success:^(SISSTenantProgressRecordInfoModel *progressInfoModel) {
        
        weakSelf.tenantProgressInfoModel = progressInfoModel;
//        if (progressInfoModel.payType == 0) {
//            weakSelf.tenantProgressInfoModel.payType = 1;
//        }
        weakSelf.bottomView.businessStatus = progressInfoModel.businessStatus;
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if (!weakSelf.isHistory) {
                weakSelf.isHistory = progressInfoModel.progress > 7;
            }
            weakSelf.bottomView.name = progressInfoModel.name;
            weakSelf.bottomView.iconUrlStr = progressInfoModel.portrait;
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView reloadData];
            
        }];
        
    } failed:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        NSLog(@"%@",error);
    }];
}


#pragma mark -- 删除请求
- (void)deleteTenantProgress {
    
    [kNetworkManager deleteTenantProgressWithArbpId:self.tenantProgressModel.arbpId successBlock:^(id responseObject) {
        
        if (self.deleteCompletedBlock) {
            self.deleteCompletedBlock();
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
}

#pragma mark -- 举报
- (void)reportTenant {
    SISSReportViewController *vc = [[SISSReportViewController alloc] init];
    vc.tenantModel = self.tenantProgressModel.rent;
    [self.navigationController pushViewController:vc animated:YES];
}


/**
 根据indexPath获取对应的时间字符串
 
 @param index index
 @return 返回对应的时间字符串
 */
- (NSString *)getTimeStrWithIndex:(NSInteger)index {
    index = self.tenantProgressModel.businessType == 2 && index > 0 ? index + 1 : index;
    NSString *timeStr;
        switch (index) {
            case 0:
                timeStr = [NSDate yyr_stringToString:self.tenantProgressInfoModel.insertTime];
                break;
            case 1:
                timeStr = [NSDate yyr_stringToString:self.tenantProgressInfoModel.recommendTime];
                break;
            case 2:
                timeStr = [NSDate yyr_stringToString:self.tenantProgressInfoModel.commissionTime];
                break;;
            case 3:
                timeStr = [NSDate yyr_stringToString:self.tenantProgressInfoModel.takelookTime];
                break;
//            case 4:
//                timeStr = [NSDate yyr_stringToString:self.tenantProgressInfoModel.leaseContractTime];
//                break;
            case 5:
                timeStr = [NSDate yyr_stringToString:self.tenantProgressInfoModel.leaseContractTime];
                break;
            case 7:
                timeStr = [NSDate yyr_stringToString:self.tenantProgressInfoModel.serviceCommentTime];
                break;
            default:
                timeStr = @" ";
                break;
        }
    return timeStr;
}


#pragma mark - navigationItem
- (void)setupNavigationItems {
    [super setupNavigationItems];
    
    self.navigationItem.rightBarButtonItem = self.isHistory ? nil : [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"more..."] style:UIBarButtonItemStylePlain target:self action:@selector(rightMoreItemClickAction)];
}


#pragma mark - UI
- (void)setupSubviews {
    [super setupSubviews];
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] init];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerClass:[SISSProgressCell class] forCellReuseIdentifier:tenantProgressCellReuseID];
    [tableView registerClass:[SISSHistoryProgressCell class] forCellReuseIdentifier:tenantHistoryProgressCellReuseID];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    SISSProgressBottomView *bottomView = [[SISSProgressBottomView alloc] init];
    bottomView.delegate = self;
    //    bottomView.name = self.tenantProgressModel.name;
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    
    // 自动布局
    WeakSelf
    CGFloat bottomViewHeight = 44.0;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(weakSelf.view);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_equalTo(bottomViewHeight);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(weakSelf.view);
        }
    }];
}

- (NSArray *)dataArr {
    if (!_dataArr) {
        
        if (self.tenantProgressModel.businessType == 1) {
            _dataArr = @[
                             @"承租方发布求租信息",
                             @"中介推荐出租房源、承租方确定意向",
                             @"上传已签署的《物业租赁承租方委托协议》",
                             @"预约-承租方实地看房",
                             @"确定租赁房源",
                             @"上传已签署的《物业租赁及经纪合同》",
                             @"出租方将物业交承租方使用",
                             @"服务评价"
                             ];
            
        } else if (self.tenantProgressModel.businessType == 2) {
            _dataArr = @[
                             @"承租方选择意向房源",
                             @"上传已签署的《物业租赁承租方委托协议》",
                             @"预约-承租方实地看房",
                             @"确定租赁房源",
                             @"上传已签署的《物业租赁及经纪合同》",
                             @"出租方将物业交承租方使用",
                             @"服务评价"
                             ];

        }
    }
    return _dataArr;
}


@end
